package com.shuyou;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.http.client.ClientProtocolException;

import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.shuyou.db.DBService;
import com.shuyou.db.Preferences;
import com.shuyou.lib.Location;
import com.shuyou.net.BookDetail;
import com.shuyou.net.Data;
import com.shuyou.net.JsonParser;
import com.shuyou.net.SearchLabel;
import com.shuyou.net.ServerInfo;
import com.shuyou.net.StaticHttpClient;
import com.shuyou.net.UserInfo;
import com.shuyou.values.Values;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.RequestType;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners.UMAuthListener;
import com.umeng.socialize.controller.listener.SocializeListeners.UMDataListener;
import com.umeng.socialize.exception.SocializeException;

import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

public class LoginActivity extends Activity implements OnClickListener {

	private static final String TAG = "LoginActivity";

	private SHARE_MEDIA whichPlatform = null;
	private String whichPlatformSign = null;

	private UMSocialService controller = null;
	private Map<String, String> map;
	private ServerInfo si = null;

	private LinearLayout loginRenren = null;
	private LinearLayout loginSina = null;
	private LinearLayout loginDouban = null;
	private ProgressBar loginProgress = null;

	private DBService dbService;

	public static boolean isHotWordsReady = false;
	
	private static Preferences pref;
	
	private LocationClient mLocClient;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_login);

		dbService = DBService.getInstance(this);
		pref = Preferences.getInstance(getApplicationContext());
		loginRenren = (LinearLayout) findViewById(R.id.login_renren);
		loginSina = (LinearLayout) findViewById(R.id.login_sina);
		loginDouban = (LinearLayout) findViewById(R.id.login_douban);
		loginProgress = (ProgressBar) findViewById(R.id.login_progressbar);

		loginRenren.setOnClickListener(this);
		loginSina.setOnClickListener(this);
		loginDouban.setOnClickListener(this);
		
		controller = UMServiceFactory.getUMSocialService("", RequestType.SOCIAL);
		
		mLocClient = ((Location)getApplication()).mLocationClient;
		((Location)getApplication()).act = LoginActivity.this;
		
		//设置定位参数
		setLocationOption();

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		loginRenren.setEnabled(false);
		loginSina.setEnabled(false);
		loginDouban.setEnabled(false);
		switch (v.getId()) {
		case R.id.login_renren:
			whichPlatform = SHARE_MEDIA.RENREN;
			whichPlatformSign = "renren";
			break;
		case R.id.login_sina:
			whichPlatform = SHARE_MEDIA.SINA;
			whichPlatformSign = "sina";
			break;
		case R.id.login_douban:
			whichPlatform = SHARE_MEDIA.DOUBAN;
			whichPlatformSign = "douban";
			break;
		default:
			break;
		}
		// 判定本地是否有信息，如果有，直接进行登录操作
		SharedPreferences sp_login = getSharedPreferences("umeng_socialize",
				Context.MODE_PRIVATE);

		String uid = sp_login.getString(whichPlatformSign, "not_exsit");

		if (uid.equals("not_exsit")) {
			doOauth();
		} else {
			doLogin(uid, whichPlatformSign);
		}
	}

	private void getHotWords(String sessionid) {
		final HashMap<String, String> map1 = new HashMap<String, String>();
		map1.put("test", "1");
		new Thread() {

			@Override
			public void run() {
				String strResult = null;
				try {
					strResult = StaticHttpClient.doGet(Values.HOTWORDS_URL, map1);
					//Log.i("jiabin", map1.get("sessionid"));
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (strResult == null) {
					Log.i("jiabin", "strResult = null");
				} else {
					//Log.i("jiabin", strResult);
					si = (ServerInfo) JsonParser.parseObject(strResult,
							ServerInfo.class);// 需要处理空指针异常
					if (si != null) { // 如果为空，当网络连接异常处理
						String status = si.getStatus();
						if (status.equals("10000"))// 操作正确
						{
							ArrayList<BookDetail> list = si.getData().getBook_list();
							dbService.saveHotWords(list);
							/*String hotJsonString = JsonParser.toJsonString(list);
							pref.saveHotWords(hotJsonString);*/
						}
					}
				}
				 
			}

		}.start();
	}
	
	private void getSearchLabel(String sessionId){
		final HashMap<String, String> map1 = new HashMap<String, String>();
		map1.put("test", "1");
		new Thread() {

			@Override
			public void run() {
				String strResult = null;
				try {
					strResult = StaticHttpClient.doGet(Values.SEARCHLABEL_URL, map1);
					//Log.i("jiabin", map1.get("sessionid"));
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (strResult == null) {
					Log.i("jiabin", "strResult = null");
				} else {
					//Log.i("jiabin", strResult);
					si = (ServerInfo) JsonParser.parseObject(strResult,
							ServerInfo.class);// 需要处理空指针异常
					if (si != null) { // 如果为空，当网络连接异常处理
						String status = si.getStatus();
						if (status.equals("10000"))// 操作正确
						{
							ArrayList<SearchLabel> list = si.getData().getLabel_list();
							dbService.saveSearchLabel(list);
						}
					}
				}
				 
			}

		}.start();
	}

	private void doLogin(final String platform_userid, String platform_kind) {
		map = new HashMap<String, String>();
		map.put("platform_userid", platform_userid);
		map.put("platform_kind", platform_kind);
		loginProgress.setVisibility(View.VISIBLE);	
		//开始定位功能
		mLocClient.start();
			
		new Thread() {

			@Override
			public void run() {
				try {
					//执行完 mLocClient.start()，先等定位功能启起来
					sleep(1000);
					
					//开始获取定位信息
					int if_location = 0;
					if (mLocClient != null && mLocClient.isStarted()){
						//位置请求，最长时间为7秒钟
						for(int i=0; i<70; i++){
						    mLocClient.requestLocation();
							if(Location.code != 0){
								if(Location.latitude!=0 && Location.lontitude!=0){
									map.put("latitude", Double.toString(Location.latitude));
									map.put("lontitude", Double.toString(Location.lontitude));
									map.put("province", Location.province);
									map.put("city", Location.city);
									map.put("region", Location.region);
									Location.latitude = 0;
									Location.lontitude = 0;
									if_location = 1;
									break;
								}
							}
						    sleep(100); //暂停，每100ms检查一次
						}
					}
					mLocClient.stop();
						
					if(if_location == 1){
						String strResult = StaticHttpClient.doPost(Values.LOGIN_URL, map);
						if (strResult == null) {
							Log.i(TAG, "strResult = null");
						} else {
							Log.i(TAG, strResult);
						}
						si = (ServerInfo) JsonParser.parseObject(strResult,ServerInfo.class);// 需要处理空指针异常
						if (si == null) { // 如果为空，当网络连接异常处理
							Log.i(TAG, "si == null");
							Message message = new Message();
							message.what = Values.NETWORK_ERROR;
							handler.sendMessage(message);
						} else {
							System.out.println(si);
							String status = si.getStatus();
							if (status.equals("10000"))// 操作正确
							{
								UserInfo.platform_userid = platform_userid; // 存储userid
								Data data = si.getData();
								if (data.getHave_info().equals("0"))// 服务器没有账户
								{
									Message message = new Message();
									message.what = Values.NEED_TO_REGISTER;
									message.obj = data.getSessionid();
									handler.sendMessage(message);
								} else if (data.getHave_info().equals("1"))// 账户已注册
								{
									Message message = new Message();
									message.what = Values.SUCCESS_TO_LOGIN;
									message.obj = data;
									handler.sendMessage(message);
								}
							} else if (status.equals("10001"))// 操作失败
							{
								Message message = new Message();
								message.obj = "操作失败";
								message.what = Values.FAIL_TO_LOGIN;
								handler.sendMessage(message);
							} else if (status.equals("10002"))// 参数错误
							{
								// TODO sth.
								Message message = new Message();
								message.obj = "参数错误";
								message.what = Values.FAIL_TO_LOGIN;
								handler.sendMessage(message);
							} else {
								// TODO sth.
								Message message = new Message();
								message.obj = "未知错误";
								message.what = Values.FAIL_TO_LOGIN;
								handler.sendMessage(message);
							}
						}
					} else {
						Location.code = 0;
						Message message = new Message();
						message.what = Values.LOCATION_ERROR;
						handler.sendMessage(message);
					}

				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					Message message = new Message();
					message.what = Values.NETWORK_ERROR;
					handler.sendMessage(message);
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					Message message = new Message();
					message.what = Values.NETWORK_ERROR;
					handler.sendMessage(message);
					e.printStackTrace();
				} catch (InterruptedException e) {
					mLocClient.stop();
			    	Message message = new Message();
					message.what = Values.LOCATION_ERROR;
					handler.sendMessage(message);
				}
			}

		}.start();
	}

	private void doOauth() {
		controller.doOauthVerify(LoginActivity.this, whichPlatform,
				new UMAuthListener() {

					@Override
					public void onStart(SHARE_MEDIA arg0) {
						// TODO Auto-generated method stub
						System.out.println("onStart");
					}

					@Override
					public void onError(SocializeException e, SHARE_MEDIA arg1) {
						// TODO Auto-generated method stub
						System.out.println("onError");
					}

					@Override
					public void onComplete(Bundle value, SHARE_MEDIA platform) {
						if (value != null
								&& !TextUtils.isEmpty(value.getString("uid"))) {
							Toast.makeText(LoginActivity.this, "授权成功.",
									Toast.LENGTH_SHORT).show();

							doLogin(value.getString("uid"), whichPlatformSign);

						} else {
							Toast.makeText(LoginActivity.this, "授权失败",
									Toast.LENGTH_SHORT).show();
						}
					}

					@Override
					public void onCancel(SHARE_MEDIA arg0) {
						// TODO Auto-generated method stub
						loginRenren.setEnabled(true);
						loginSina.setEnabled(true);
						loginDouban.setEnabled(true);
						System.out.println("onCancel");
					}
				});
	}

	/**
	 * 更具已经具有的sessionid跳转到RegisterActivity.java页面，进行个人信息的注册
	 * 
	 * @param sessionid
	 */
	private void gotoPersonalInfo(final String sessionid) {
		controller.getPlatformInfo(LoginActivity.this, whichPlatform,
				new UMDataListener() {

					@Override
					public void onStart() {
						// TODO Auto-generated method stub
					}

					@Override
					public void onComplete(int status, Map<String, Object> info) {
						if (status == 200 && info != null) {
							StringBuilder sb = new StringBuilder();
							Set<String> keys = info.keySet();
							for (String kStr : keys) {
								sb.append(kStr + "="
										+ info.get(kStr).toString() + "\r\n");
							}
							Log.d("TestData", sb.toString());
							Intent i = new Intent(LoginActivity.this,
									RegisterActivity.class);
							i.putExtra("uid", info.get("uid").toString());
							if(whichPlatformSign == "douban"){
								i.putExtra("sex", "0");
							}else{
								i.putExtra("sex", info.get("gender").toString());
							}
							i.putExtra("nickname", info.get("screen_name")
									.toString());
							i.putExtra("sessionid", sessionid);
							i.putExtra("platform_kind", whichPlatformSign);
							startActivityForResult(i, 1);
						} else
							Toast.makeText(getApplicationContext(),
									"发生错误" + status, Toast.LENGTH_SHORT).show();
					}
				});
	}

	// 静态handler,防止内存泄漏错误
	static class MyInnerHandler extends Handler {
		WeakReference<LoginActivity> mActivity;

		MyInnerHandler(LoginActivity mAct) {
			mActivity = new WeakReference<LoginActivity>(mAct);
		}

		@Override
		public void handleMessage(Message msg) {
			LoginActivity theAct = mActivity.get();
			switch (msg.what) {
			case Values.FAIL_TO_LOGIN:
				Toast.makeText(theAct, "登录失败" + msg.obj.toString(),
						Toast.LENGTH_SHORT).show();
				theAct.loginProgress.setVisibility(View.INVISIBLE);
				theAct.loginRenren.setEnabled(true);
				theAct.loginSina.setEnabled(true);
				theAct.loginDouban.setEnabled(true);
				break;
			case Values.SUCCESS_TO_LOGIN:
				// 进入首页，已有booklist等等
				Data data = (Data)msg.obj;
				theAct.getHotWords(data.getSessionid());
				theAct.getSearchLabel(data.getSessionid());
				Intent i = new Intent(theAct, MainActivity.class);
				i.putExtra("data", data);
				theAct.startActivityForResult(i, 0);
				break;
			case Values.NEED_TO_REGISTER:
				String sessionid = msg.obj.toString();
				theAct.gotoPersonalInfo(sessionid);
				break;
			case Values.NETWORK_ERROR:
				Toast.makeText(theAct, "网络连接错误", Toast.LENGTH_SHORT).show();
				theAct.loginProgress.setVisibility(View.INVISIBLE);
				theAct.loginRenren.setEnabled(true);
				theAct.loginSina.setEnabled(true);
				theAct.loginDouban.setEnabled(true);
				break;
			case Values.LOCATION_ERROR:
				Toast.makeText(theAct, "位置信息获取失败", Toast.LENGTH_LONG).show();
				theAct.loginProgress.setVisibility(View.INVISIBLE);
				theAct.loginRenren.setEnabled(true);
				theAct.loginSina.setEnabled(true);
				theAct.loginDouban.setEnabled(true);
				break;
			default:
				break;
			}
		}
	}

	MyInnerHandler handler = new MyInnerHandler(this);

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		finish();
	}
	
	private void setLocationOption(){
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);
		option.setAddrType("all");//返回的定位结果包含地址信息
		option.setCoorType("bd09");//返回的定位结果是百度经纬度,默认值gcj02
		option.setScanSpan(100);//设置发起定位请求的间隔时间,如果该值小于1000,app主动定位
		option.disableCache(true);//禁止启用缓存定位
		option.setPoiNumber(0);    //最多返回POI个数   
		option.setPoiExtraInfo(false); //是否需要POI的电话和地址等详细信息        
		mLocClient.setLocOption(option);
	}
}
